/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.realbrand.net.realbrandpay.zxing.app;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.base.FirstActivity;
import com.realbrand.net.realbrandpay.bean.ShopcarBean;
import com.realbrand.net.realbrandpay.bean.VersionBean;
import com.realbrand.net.realbrandpay.db.DBManger;
import com.realbrand.net.realbrandpay.inter.IGetPickCodeInfo;
import com.realbrand.net.realbrandpay.inter.IScanCommodity;
import com.realbrand.net.realbrandpay.inter.IVersion;
import com.realbrand.net.realbrandpay.test.TestActivity;
import com.realbrand.net.realbrandpay.ui.activity.ADSActivity;
import com.realbrand.net.realbrandpay.ui.activity.OneActivity;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.mall.MallActivity;
import com.realbrand.net.realbrandpay.ui.activity.pickcode.PickCodeActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CommodityDetailsActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.ShopCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.camera.CameraManager;
import com.realbrand.net.realbrandpay.zxing.decoding.CaptureActivityHandler;
import com.realbrand.net.realbrandpay.zxing.decoding.InactivityTimer;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.realbrand.net.realbrandpay.zxing.util.Utils;
import com.realbrand.net.realbrandpay.zxing.view.ViewfinderView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * The barcode reader activity itself. This is loosely based on the
 * CameraPreview example included in the Android SDK.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public class CaptureActivity extends FirstActivity implements SurfaceHolder.Callback,
        OnClickListener {

    @BindView(R.id.capture_tv_mall)
    TextView captureTvMall;
    @BindView(R.id.capture_tv_shop)
    TextView captureTvShop;
    @BindView(R.id.capture_tv_my)
    TextView captureTvMy;
    private CaptureActivityHandler handler;// 消息中心
    private ViewfinderView viewfinderView;// 绘制扫描区域
    private boolean hasSurface;// 控制调用相机属性
    private Vector<BarcodeFormat> decodeFormats;// 存储二维格式的数组
    private String characterSet;// 字符集
    private InactivityTimer inactivityTimer;// 相机扫描刷新timer
    private MediaPlayer mediaPlayer;// 播放器
    private boolean playBeep;// 声音布尔
    private static final float BEEP_VOLUME = 0.10f;// 声音大小
    private boolean vibrate;// 振动布尔
    private Toolbar scanToolBar;
    // 闪光灯
    private Button flash_btn;
    private boolean isTorchOn = true;

    //传到商品列表界面的扫描结果的KEY
    public static final String DATA_KEY = "SCAN_RESULT";

    //传到商品列表界面的对象的key
    public static final String BEAN_KEY = "bean";

    //商家是否支持微信支付
    public static boolean supportWX = false;
    //商家是否支持支付宝支付
    public static boolean supportAlipay = false;
    //商家是否支持龙支付
//    public static boolean supportJianHang = false;

    String bundleValue;
    //是否需要获取本地版本信息
    public static boolean isGetVersion = true;
    public AlertDialog dialog;
    SharedPreferences sharedPreferences;
    //是否选择不要提示
    public boolean isCheck;
    public static boolean aBoolean = true;
    APP app;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);

        scanToolBar = (Toolbar) findViewById(R.id.captureActivity_toolbar);
        scanToolBar.setTitle("");
        TextView textView = (TextView) scanToolBar.findViewById(R.id.textview_title);
        //获取bundleValue，判断是否是从广告页面跳转过来的，如果是则不显示返回按钮，如果不是则显示返回按钮
        Bundle bundle = getIntent().getExtras();
        bundleValue = bundle.getString(Static.BundleKey, "");
        L.d(L.TAG, "bundleValue:" + bundleValue);
        if (bundleValue.equals(Static.BundleValue)) {
//            scanToolBar.setNavigationIcon(R.mipmap.ic_back);
            textView.setText("商品检索");

        } else if (bundleValue.equals(Static.VALUE_SCANMERCHANT)) {
//            scanToolBar.setNavigationIcon(R.mipmap.ic_back);
            textView.setText("扫描商家二维码");
        }
        //创建一个数组，用来装所有扫过的二维码
//        list = new ArrayList<String>();
//        app = (APP) getApplicationContext();
        setSupportActionBar(scanToolBar);
        getVersion();
        setOnClick();
        CameraManager.init(this);
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        inactivityTimer = new InactivityTimer(this);
        //判断是否弹出更新版本提示
        sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
        int VersionCompare = sharedPreferences.getInt(Constant.VersionCompare, 0);
        int VersionUpData = sharedPreferences.getInt(Constant.VersionUpData, 0);
        String VersionUpDataUrl = sharedPreferences.getString(Constant.VersionUpDataUrl, "");
        if (VersionCompare < VersionUpData && OneActivity.aBoolean) {
            L.d(L.TAG, "ture" + OneActivity.aBoolean);
            //提示版本更新
            if (!VersionUpDataUrl.equals("")) {
                updataDialog(VersionUpDataUrl, VersionUpData);
            }
        }
    }

    /**
     * 获取服务器上版本信息
     */
    private void getVersion() {
        IVersion iVersion = HttpRequest.request_BASE_URL_VERSION(IVersion.class, HTTPAPI.BASE_URL_VERSION);
        iVersion.getVersion()
                .subscribeOn(Schedulers.newThread())//请求在新线程中执行
                .observeOn(Schedulers.io())//请求完成后再IO中执行
                .doOnNext(new Action1<VersionBean>() {
                    @Override
                    public void call(VersionBean versionBean) {
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//最后再主线程中执行
                .subscribe(new Subscriber<VersionBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(VersionBean versionBean) {
                        L.d(L.TAG, "版本信息" + versionBean.getVersionCode());
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putInt(Constant.VersionUpData, versionBean.getVersionCode());
                        edit.putString(Constant.VersionUpDataUrl, versionBean.getUrl());
                        L.d(L.TAG, "下载地址" + versionBean.getUrl());
                        if (isGetVersion) {
                            int appLocalVersion = Static.getAPPLocalVersion(CaptureActivity.this);
                            //保存本地版本号
                            edit.putInt(Constant.VersionBenDi, appLocalVersion);
                            edit.putInt(Constant.VersionCompare, appLocalVersion);
                            edit.commit();
                        }

                    }
                });


    }

    /**
     * 提示版本更新
     *
     * @param versionUpDataUrl 下载最新版本的URL
     * @param versionUpData
     */
    private void updataDialog(final String versionUpDataUrl, final int versionUpData) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.updata_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        dialog = builder.create();
        dialog.setView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        TextView cancel = (TextView) view.findViewById(R.id.dialog_updata_cancel);
        TextView upData = (TextView) view.findViewById(R.id.dialog_updata_updata);
        CheckBox noHint = (CheckBox) view.findViewById(R.id.dialog_updata_noHint);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                OneActivity.aBoolean = false;
                dialog.dismiss();
            }
        });
        upData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //更新app
                Static.upDataAPP(versionUpDataUrl, versionUpData, CaptureActivity.this);
                L.d(L.TAG, "点击更新");
                dialog.dismiss();
                OneActivity.isGetVersion = true;
                isCheck = false;
            }
        });
        noHint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isCheck = true;
                    OneActivity.isGetVersion = false;
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putInt(Constant.VersionCompare, versionUpData);
                    edit.commit();
                }
            }
        });
        if (isCheck) {
            OneActivity.isGetVersion = false;
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putInt(Constant.VersionCompare, versionUpData);
            edit.commit();
        }
        dialog.show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qrcode_capture_layout;
    }

    @Override
    protected void setOnClick() {
        //设置返回按钮的监听
//        scanToolBar.setNavigationOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        captureTvMall.setOnClickListener(this);
        captureTvMy.setOnClickListener(this);
        captureTvShop.setOnClickListener(this);
        //点击跳转到钱包界面
//        mImageView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (LoginActivity.isLogin) {
//                    startActivity(new Intent(CaptureActivity.this, WalletActivity.class));
//                    finish();
//                } else {
//                    startActivity(new Intent(CaptureActivity.this, WalletLogoutActivity.class));
//                    finish();
//                }
//            }
//        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 初始化相机画布
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;
        // 声音
        playBeep = true;
        // 初始化音频管理器
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        // 振动
        vibrate = true;

    }

    @Override
    protected void onPause() {

        // 停止相机 关闭闪光灯
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {

        // 停止相机扫描刷新timer
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (resultString.equals("")) {
            Toast.makeText(this, "扫描失败!", Toast.LENGTH_SHORT)
                    .show();
        } else if (resultString.indexOf("UserAccount") != -1) {
            //表示示扫的是商家收款二维码
            L.d(L.TAG, resultString);
            //截取过后的二维码数据
            String scanMerchant = resultString.substring(resultString.lastIndexOf(":") + 1, resultString.length());
            L.d(L.TAG, "截取过后的二维码" + scanMerchant);
            Intent intent = new Intent(this, ShopCarActivity.class);
            //根据bundleValue判断如果不是从购物车界面跳转过来的话，那就使用startActivity，反之则使用setResult。
            if (bundleValue.equals(Static.VALUE_SCANMERCHANT)) {
                Bundle bundle = new Bundle();
                bundle.putString(Static.VALUE_SCANMERCHANT, scanMerchant);
                intent.putExtras(bundle);
                setResult(ShopCarActivity.SCAN_RESULT, intent);
                finish();
            } else {
                intent.putExtra("scanMer", scanMerchant);
                startActivity(intent);
                finish();
            }
        } else if (resultString.indexOf("test:") != -1) {
            Intent intent = new Intent(CaptureActivity.this, TestActivity.class);
            startActivity(intent);
            finish();
        } else if (resultString.indexOf("c:") != -1) {//表示商品码
            String scanCommodity = resultString.substring(resultString.lastIndexOf(":") + 1, resultString.length());
            L.d(L.TAG, "商品码" + scanCommodity);
//            list.add(scanCommodity);
//            app.setList(list);
//            Log.d("z", "扫过的二维码个数" + list.toString() + "个数" + list.size());
            ShopcarBean bean = new ShopcarBean();
            setDatas(scanCommodity, bean);//将数据存到数据库
        } else if (resultString.indexOf("p:") != -1) {//表示包装码
            String scanPickCode = resultString.substring(resultString.lastIndexOf(":") + 1, resultString.length());
            getPickData(scanPickCode);
        } else {
            L.d(L.TAG, resultString);
            Static.toast(this, "二维码不能识别，请重新扫码");
            SystemClock.sleep(1000);
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            initCamera(surfaceHolder);
            if (handler != null)
                handler.restartPreviewAndDecode();
        }
    }

    /**
     * 获取包装码数据
     *
     * @param scanPickCode
     */
    private void getPickData(String scanPickCode) {
        JSONObject object = new JSONObject();
        try {
            object.put("SOURCE", "CaptureActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("METHOD", "GetPackingInfo");
            object.put("PackingCode", scanPickCode);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            L.d(L.TAG, "包装码请求参数" + object.toString());
            IGetPickCodeInfo iGetPickCodeInfo = HttpRequest.request_BASE_URL_VERSION(IGetPickCodeInfo.class, HTTPAPI.BASE_URL);
            iGetPickCodeInfo.getDatas(body).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        if (response == null) {
                            Static.toast(CaptureActivity.this, "网络繁忙");

                        } else {
                            String string = response.body().string();
                            L.d(L.TAG, "包装码返回的结果" + string);
                            if (TextUtils.isEmpty(string)) {
                                Static.toast(CaptureActivity.this, "网络繁忙");
                            } else {
                                //跳转到商品确认页面
                                if (bundleValue.equals(OneActivity.VALUE_ADS)) {
                                    Intent intent = new Intent(CaptureActivity.this, PickCodeActivity.class);
                                    intent.putExtra("pickCode", string);
                                    startActivity(intent);
                                    finish();
                                } else if (bundleValue.equals("pickCode")) {
                                    Intent intent = new Intent(CaptureActivity.this, PickCodeActivity.class);
                                    intent.putExtra("pickCode", string);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        L.d(L.TAG, "包装码返回的结果异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    L.d(L.TAG, "包装码请求失败" + t.toString());
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            L.d(L.TAG, "包装码返回的参数异常" + e.toString());
        }
    }

    /**
     * 设置模拟数据
     *
     * @param resultString
     * @param bean
     */
    List<String> list;

    private void setDatas(final String resultString, final ShopcarBean bean) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("SOURCE", "CaptureActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "GetCommodityInfo");
            jsonObject.put("CommodityCode", resultString);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IScanCommodity iScanCommodity = retrofit.create(IScanCommodity.class);
            Call<ResponseBody> call = iScanCommodity.getDatas(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.body() == null) {
                        Static.toast(CaptureActivity.this, "网络繁忙");
                    } else {
                        try {


                            String commodityInfo = response.body().string();
                            Log.d(L.TAG, "上传二维码获取的商品信息" + commodityInfo);
                            try {
                                JSONObject object = new JSONObject(commodityInfo);
                                String scanState = object.getString("ScanState");
                                String scanTime = object.getString("ScanTime");
                                JSONObject json = object.getJSONArray("DATA").getJSONObject(0);
                                String commodityName = json.getString("CommodityName");
                                String supplyMoney = json.getString("SupplyMoney");
                                String enterpriseName = json.getString("EnterpriseName");
                                String UserAdress = json.getString("UserAddress");
                                String activationtime = json.getString("ActivationTime");
                                String productionAddress = json.getString("ProductionAddress");
                                String commodityProfile = json.getString("CommodityProfile");
                                String filePath = json.getString("FilePath");
                                String applyUser = json.getString("UserAccount");
                                String scanFrequency = json.getString("ScanFrequency");
                                //判断商家支持哪几种支付方式
                                JSONArray bankName = json.getJSONArray("BankName");
                                for (int i = 0; i < bankName.length(); i++) {
                                    if (bankName.getString(i).equals("微信")) {
                                        APP.supportWX = true;
                                    } else if (bankName.getString(i).equals("支付宝")) {
                                        APP.supportAlipay = true;
                                    } else {
                                        APP.supportAlipay = false;
                                        APP.supportWX = false;
                                    }
//                                    else if (bankName.getString(i).equals("龙支付")) {
//                                        supportJianHang = true;
//                                    }
                                }
                                Log.d(L.TAG, "添加到数据库的数据" + commodityInfo + supplyMoney + enterpriseName + UserAdress + activationtime + productionAddress);
                                bean.setName(commodityName);
                                bean.setDrawableId(filePath);
                                bean.setAdress(UserAdress);
                                bean.setPrice(supplyMoney);
                                bean.setScan(resultString);
                                bean.setStore(enterpriseName);
                                bean.setActivationTime(activationtime);
                                bean.setProductionAdress(productionAddress);
                                bean.setCommodityProfile(commodityProfile);
                                bean.setApplyUser(applyUser);
                                bean.setScanStatte(scanState);
                                bean.setScanFrequency(scanFrequency);
                                bean.setScanTime(scanTime);
                                if (bean.getScanStatte().equals("1")) {
                                    Intent intent = new Intent(CaptureActivity.this, CommodityDetailsActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("bean", bean);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else {
                                    Log.d(L.TAG, "对象" + bean.toString());
                                    DBManger dbManger = new DBManger(CaptureActivity.this);
//                                dbManger.insertsqllist(bean);
                                    if (dbManger.search_scan(bean.getScan())) {
                                    } else {
                                        Log.d(L.TAG, "表示数据库没有该条数据，添加到该数据库");
                                        dbManger.insertsqllist(bean);
                                    }
                                    Intent data = new Intent(CaptureActivity.this, ShopCarActivity.class);
                                    if (bundleValue.equals(ADSActivity.VALUE_ADS) || bundleValue.equals("pickCode")) {
                                        startActivity(data);
                                        finish();
                                    } else {
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable(BEAN_KEY, bean);
                                        data.putExtras(bundle);
                                        setResult(Activity.RESULT_OK, data);
                                        finish();
                                    }
                                }
                            } catch (JSONException e) {
                                Log.d(L.TAG, "json异常" + e.toString());
                                e.printStackTrace();

                            }
                        } catch (IOException e) {
                            Log.d(L.TAG, "IO异常" + e.toString());
                            e.printStackTrace();

                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.d("zhu", "请求失败" + t.toString());
                    finish();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            L.d(L.TAG, "扫码" + e.toString());
        }
    }


    /**
     * 初始化相机
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    /**
     * 声音设置
     */
    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    /**
     * 结束后的声音
     */
    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private static final int REQUEST_CODE = 234;// 相册选择code
    private String photo_path;// 选择图片的路径

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            switch (requestCode) {

                case REQUEST_CODE:

                    String[] proj = {MediaStore.Images.Media.DATA};
                    // 获取选中图片的路径
                    Cursor cursor = getContentResolver().query(data.getData(),
                            proj, null, null, null);

                    if (cursor.moveToFirst()) {

                        int column_index = cursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(column_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(),
                                    data.getData());
                        }

                    }

                    cursor.close();

                    releaseImgThread();

                    break;

            }

        }

    }

    /**
     * 解析图片Thread
     */
    private void releaseImgThread() {
        new Thread(new Runnable() {

            @Override
            public void run() {

                Result result = Utils.scanningImage(photo_path);
                if (result == null) {
                    msgHandler.sendEmptyMessage(SHOW_TOAST_MSG);

                } else {
                    // 数据返回

                    String recode = Utils.recode(result.toString());

                    Intent data = new Intent();
                    data.putExtra("LOCAL_PHOTO_RESULT", recode);
                    setResult(300, data);
                    finish();

                }
            }
        }).start();
    }

    private static final int SHOW_TOAST_MSG = 0;
    Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_TOAST_MSG:

                    Toast.makeText(getApplicationContext(), "未发现二维码图片", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }

        ;
    };

    /*
     * onClick
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.capture_tv_mall:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, MallActivity.class));
                    finish();
                } else {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    intent1.putExtra("whereActivity", "WalletLogout");
                    startActivity(intent1);
                    finish();
                }
                break;
            case R.id.capture_tv_my:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, WalletActivity.class));
                } else {
                    startActivity(new Intent(this, WalletLogoutActivity.class));
                }
                finish();
                break;
            case R.id.capture_tv_shop:
                startActivity(new Intent(this, ShopCarActivity.class));
                finish();
                break;
            default:
                break;
        }

    }


}